/**
 * Project:TODO ADD PROJECT NAME
 * Modify Information:
 * ================================================================
 * Author         Date           Description
 * ------------   ----------      --------------------------------
 * songyf        2023/4/19         TODO:
 * ================================================================
 * Copyright (c) 银联商务股份有限公司 www.chinaums.com
 */
package language.jndi;

import com.sun.jndi.dns.DnsContext;
import org.junit.Test;

import javax.naming.Context;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Hashtable;

public class DnsJndiExample {
    public static void main(String[] args) {
        try {
            // 创建DNS上下文对象
            Hashtable<String, String> env = new Hashtable<>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
            DirContext ctx = new InitialDirContext(env);

            // 查询主机名对应的IP地址
            String hostName = "www.example.com";

            // getAttributes方法适用于获取指定主机名的多种属性信息
            String[] attrs = { "A","TXT","MX" };
            Attributes attrsSet = ctx.getAttributes(hostName, attrs);
            Attribute attr = attrsSet.get("A");
            if (attr != null) {
                for (int i = 0; i < attr.size(); i++) {
                    System.out.println(attr.get(i).toString());
                }
            }

            //DnsContext用于连接和交互DNS服务器
            DnsContext obj = (DnsContext)ctx.lookup(hostName);
            System.out.println(obj);

            // 关闭DNS上下文对象
            ctx.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void useDNS() throws UnknownHostException {
        // 查询主机名对应的IP地址
        String hostName = "www.example.com";
        InetAddress[] addresses = InetAddress.getAllByName(hostName);
        for (int i = 0; i < addresses.length; i++) {
            System.out.println(hostName + " has address " + addresses[i].getHostAddress());
        }
    }
}
